package com.gzc.just.play.last.war.loginserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.loginserver.service.AuthService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 密码重置处理器
 * 处理密码重置请求
 */
@Component
public class PasswordResetHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(PasswordResetHandler.class);
    
    @Autowired
    private AuthService authService;
    
    private static final int PASSWORD_RESET = 4005;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从消息中解析操作类型
        String operation = extractOperation(message);
        
        switch (operation) {
            case "requestReset":
                handleRequestReset(message, ctx);
                break;
            case "verifyCode":
                handleVerifyCode(message, ctx);
                break;
            case "resetPassword":
                handleResetPassword(message, ctx);
                break;
            default:
                logger.warn("Unknown password reset operation: {}", operation);
                break;
        }
    }
    
    /**
     * 处理密码重置请求
     */
    private void handleRequestReset(Object message, ChannelHandlerContext ctx) {
        // 从消息中解析邮箱或用户名
        String emailOrUsername = extractEmailOrUsername(message);
        
        // 验证输入
        if (emailOrUsername == null || emailOrUsername.trim().isEmpty()) {
            sendPasswordResetResponse(ctx, null, false, "Email or username is required");
            return;
        }
        
        // 请求密码重置
        Map<String, Object> result = authService.requestPasswordReset(emailOrUsername);
        
        // 检查结果
        boolean success = (Boolean) result.getOrDefault("success", false);
        String messageStr = (String) result.getOrDefault("message", "Password reset request failed");
        
        // 发送响应
        if (success) {
            logger.info("Password reset requested for: {}", emailOrUsername);
        } else {
            logger.warn("Password reset request failed for: {}, reason: {}", emailOrUsername, messageStr);
        }
        
        sendPasswordResetResponse(ctx, result, success, messageStr);
    }
    
    /**
     * 处理验证码验证
     */
    private void handleVerifyCode(Object message, ChannelHandlerContext ctx) {
        // 从消息中解析邮箱和验证码
        String email = extractEmail(message);
        String code = extractVerificationCode(message);
        
        // 验证输入
        if (email == null || email.trim().isEmpty() || 
            code == null || code.trim().isEmpty()) {
            sendPasswordResetResponse(ctx, null, false, "Email and verification code are required");
            return;
        }
        
        // 验证验证码
        Map<String, Object> result = authService.verifyResetCode(email, code);
        
        // 检查结果
        boolean success = (Boolean) result.getOrDefault("success", false);
        String messageStr = (String) result.getOrDefault("message", "Verification failed");
        
        // 发送响应
        if (success) {
            logger.info("Password reset code verified for: {}", email);
        } else {
            logger.warn("Password reset code verification failed for: {}, reason: {}", email, messageStr);
        }
        
        sendPasswordResetResponse(ctx, result, success, messageStr);
    }
    
    /**
     * 处理密码重置
     */
    private void handleResetPassword(Object message, ChannelHandlerContext ctx) {
        // 从消息中解析邮箱、验证码和新密码
        String email = extractEmail(message);
        String code = extractVerificationCode(message);
        String newPassword = extractNewPassword(message);
        
        // 验证输入
        if (email == null || email.trim().isEmpty() || 
            code == null || code.trim().isEmpty() ||
            newPassword == null || newPassword.trim().isEmpty()) {
            sendPasswordResetResponse(ctx, null, false, "Email, verification code and new password are required");
            return;
        }
        
        // 验证新密码格式
        if (!validatePassword(newPassword)) {
            sendPasswordResetResponse(ctx, null, false, "Password must be at least 6 characters");
            return;
        }
        
        // 重置密码
        Map<String, Object> result = authService.resetPassword(email, code, newPassword);
        
        // 检查结果
        boolean success = (Boolean) result.getOrDefault("success", false);
        String messageStr = (String) result.getOrDefault("message", "Password reset failed");
        
        // 发送响应
        if (success) {
            logger.info("Password reset successful for: {}", email);
        } else {
            logger.warn("Password reset failed for: {}, reason: {}", email, messageStr);
        }
        
        sendPasswordResetResponse(ctx, result, success, messageStr);
    }
    
    private String extractOperation(Object message) {
        // 实际实现中应该从消息对象中解析操作类型
        // 这里返回示例值
        return "requestReset";
    }
    
    private String extractEmailOrUsername(Object message) {
        // 实际实现中应该从消息对象中解析邮箱或用户名
        // 这里返回示例值
        return "user@example.com";
    }
    
    private String extractEmail(Object message) {
        // 实际实现中应该从消息对象中解析邮箱
        // 这里返回示例值
        return "user@example.com";
    }
    
    private String extractVerificationCode(Object message) {
        // 实际实现中应该从消息对象中解析验证码
        // 这里返回示例值
        return "123456";
    }
    
    private String extractNewPassword(Object message) {
        // 实际实现中应该从消息对象中解析新密码
        // 这里返回示例值
        return "newpass123";
    }
    
    private boolean validatePassword(String password) {
        // 密码验证规则：至少6个字符
        return password != null && password.length() >= 6;
    }
    
    private void sendPasswordResetResponse(ChannelHandlerContext ctx, Map<String, Object> result, 
                                        boolean success, String message) {
        // 实际实现中应该构造并发送密码重置响应消息
        logger.info("Sending password reset response: success={}, message={}", success, message);
        
        // 示例：打印响应内容（实际实现中应该将结果序列化为响应消息）
        if (success && result != null) {
            logger.debug("Password reset result content:");
            for (Map.Entry<String, Object> entry : result.entrySet()) {
                if (!"password".equals(entry.getKey())) { // 不打印密码
                    logger.debug("{}: {}", entry.getKey(), entry.getValue());
                }
            }
        }
    }

    @Override
    public int getMessageId() {
        return PASSWORD_RESET;
    }
    
    @Override
    public String getName() {
        return "PasswordResetHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}